<?php

namespace Frame\LLOneBot\Lib;

use app\MessageHandler;
use app\core\App;

use app\core\Log;

class MessageHandle extends MessageHandler
{

    /**
     * 消息数组
     * @var 
     */
    public $message;

    /**
     * 响应类
     * @var 
     */
    public $Response;

    /**
     * 词库实例
     * @var 
     */
    public $method;

    /**
     * @var string 指令前缀
     */
    public $prefix = 'QR_';


    public function handle()
    {
        //获取响应类实例
        $this->Response = App::_getResponseClass();
        print_r($this->message);
        foreach ($this->classList as $className => $fileName) {
            if (!class_exists($className)) {
                //类不存在
                continue;
            }
            //实例化词库类
            $this->method = new $className();
            foreach ($this->method->instruction as $pattern => $callback) {
                //获取正则表达式
                $regex = $this->formatPattern($pattern);
                echo $regex;
                if (preg_match($regex, $this->message['msg'], $matches)) {

                    if ($this->executeCallback($callback, $matches)) {

                    }
                }
            }
            //print_r($method);
        }

        print_r(Log::getLog());
    }


    /**
     * 执行指令
     * @param mixed $methodName
     * @param mixed $matches
     */
    public function executeCallback($methodName, $matches = [])
    {

        if (!method_exists($this->method, $methodName)) {
            //方法不存在
            return false;
        }

        //括号
        $this->method->bracket = $matches;
        $params = explode(' ', $this->message['msg']);
        $params[-1] = $this->message['msg'];
        //参数
        $this->method->matches = $params;

        //执行指令
        $result = $this->method->$methodName();

        if (!empty($result) && !isset($_GET['msg'])) {
            if (is_json($result) && method_exists($this->Response, 'sendJson')) {
                //发送json消息
                $this->Response->sendJson([
                    'message_type' => $this->message['type'],
                    'user_id' => $this->message['uin'],
                    'group_id' => $this->message['gin'],
                    'message' => $result
                ]);
            } else {
                //发送消息
                $this->Response->sendMsg([
                    'message_type' => $this->message['type'],
                    'user_id' => $this->message['uin'],
                    'group_id' => $this->message['gin'],
                    'message' => $result
                ]);

            }

            return true;
        } else {
            print_r($result);
        }
    }

}